const { createApp } = Vue;

createApp({
    data() {
        return {
            form: {
                username: '',
                password: ''
            },
            loading: false,
            showPassword: false
        }
    },
    methods: {
        togglePassword() {
            this.showPassword = !this.showPassword;
        },
        
        async handleLogin() {
            if (!this.form.username || !this.form.password) {
                Swal.fire({
                    icon: 'warning',
                    title: '请填写完整',
                    text: '用户名和密码不能为空'
                });
                return;
            }

            this.loading = true;
            
            try {
                const response = await fetch('/api/admin/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.form)
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    // 登录成功
                    Swal.fire({
                        icon: 'success',
                        title: '登录成功',
                        text: '正在跳转...',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        // 跳转到后台首页
                        window.location.href = '/index';
                    });
                } else {
                    throw new Error(data.msg || '登录失败');
                }
            } catch (error) {
                console.error('登录失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '登录失败',
                    text: error.message || '请检查用户名和密码是否正确'
                });
            } finally {
                this.loading = false;
            }
        }
    },
    mounted() {
        // 检查是否已登录
        fetch('/api/admin/check-login')
            .then(res => res.json())
            .then(data => {
                if (data.code === 200) {
                    // 已登录则直接跳转
                    window.location.href = 'templates.html';
                }
            })
            .catch(console.error);
    }
}).mount('#loginApp'); 